package com.lizhaoshan.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.lizhaoshan.dao.DishDao;
import com.lizhaoshan.dao.DishFlavorDao;
import com.lizhaoshan.dto.DishDto;
import com.lizhaoshan.dto.DishFlavorsDto;
import com.lizhaoshan.pojo.Dish;
import com.lizhaoshan.pojo.DishFlavor;
import com.lizhaoshan.pojo.PageBean;
import com.lizhaoshan.service.DishService;
import com.lizhaoshan.vo.DishVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @program: reggie
 * @description:
 * @author: lamour
 * @create: 2022-05-14 17:19
 **/

@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishDao dishDao;

    @Autowired
    private DishFlavorDao dishFlavorDao;

    @Override
    public boolean addDish(DishDto dishDto) {

        String id = new Snowflake().nextIdStr();
        dishDto.setId(id);

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        String format = dtf.format(LocalDateTime.now());
        dishDto.setUpdateTime(format);
        dishDto.setCreateTime(format);
        // String employeeId = TokenHolder.getCurrentId();
        dishDto.setCreateUser(id);
        dishDto.setUpdateUser(id);
        dishDto.setSort(1);
        dishDto.setIsDeleted(0);
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDto, dish);

        List<DishFlavorsDto> flavors = dishDto.getFlavors();
        if (CollUtil.isEmpty(flavors)) {
            return false;
        }
        List<DishFlavor> flavorsList = new ArrayList<>();
        for (DishFlavorsDto flavorsDto : flavors) {
            DishFlavor dishFlavor = new DishFlavor();
            BeanUtils.copyProperties(flavorsDto, dishFlavor);

            String did = new Snowflake().nextIdStr();
            dishFlavor.setId(did);

            dishFlavor.setDishId(id);

            dishFlavor.setCreateTime(dishDto.getCreateTime());
            dishFlavor.setUpdateTime(dishDto.getUpdateTime());

            dishFlavor.setCreateUser(dishDto.getCreateUser());
            dishFlavor.setUpdateUser(dishDto.getUpdateUser());

            dishFlavor.setIsDeleted(dishDto.getIsDeleted());

            flavorsList.add(dishFlavor);
        }

        int insert = dishDao.insert(dish);
        int insertBatch = dishFlavorDao.insertBatch(flavorsList);
        return insert == flavorsList.size() && insertBatch > 0;
    }

    @Override
    public boolean putDish(DishDto dishDto) {
        //获取dish的id,用于判断该id的dish是否存在，并将创建人和创建时间赋值给口味
        String dishId = dishDto.getId();

        log.info("********通过id查找数据库中的dish，begin");
        Dish dish = dishDao.selectById(dishId);
        log.info("********通过id查找数据库中的dish，end");
        if (Objects.isNull(dish)) {
            return false;
        }

        //用户可能新增口味，所以不能仅仅修改口味
        log.info("********通过dish_Id删除flavor，重新添加的方式代替修改");
        int deleteById = dishFlavorDao.deleteByDishId(dishId);
        log.info("********删除flavor，end");

        ArrayList<DishFlavor> flavorsList = new ArrayList<>();

        //获取前端传进来的口味，进行判空
        List<DishFlavorsDto> flavorsDto = dishDto.getFlavors();
        if (CollUtil.isEmpty(flavorsDto)) {
            return false;
        }
        for (DishFlavorsDto flavorDto : flavorsDto) {
            if (Objects.isNull(flavorDto)) {
                continue;
            }
            //设置flavor的id
            String fid = new Snowflake().nextIdStr();
            flavorDto.setId(fid);
            flavorDto.setDishId(dishId);
            //设置修改时间
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
            String format = dtf.format(LocalDateTime.now());
            flavorDto.setCreateTime(format);
            flavorDto.setUpdateTime(format);

            //设置修改用户
            flavorDto.setCreateUser(dish.getCreateUser());
            flavorDto.setUpdateUser(dish.getUpdateUser());

            //设置是否删除
            // flavorDto.setIsDeleted(dishDto.getIsDeleted());
            flavorDto.setIsDeleted(0);

            //flavors的拷贝
            DishFlavor flavors = new DishFlavor();
            BeanUtils.copyProperties(flavorDto, flavors);
            flavorsList.add(flavors);
        }

        //设置dish的flavors的属性
        dishDto.setFlavors(flavorsDto);

        //批量添加flavor表
        log.info("**********批量添加flavor，begin");
        int insertBatch = dishFlavorDao.insertBatch(flavorsList);
        log.info("**********批量添加flavor，end");

        //修改dish表
        Dish dish2 = new Dish();
        BeanUtils.copyProperties(dishDto, dish2);
        log.info("**********修改dish表，begin");
        int update = dishDao.update(dish2);
        log.info("**********修改dish表，end");

        return deleteById == flavorsList.size() && insertBatch == flavorsList.size() && update > 0;
    }

    @Override
    public boolean deleteByIds(List<String> idsList) {
        if (CollUtil.isEmpty(idsList)) {
            return false;
        }

        //统计符合dishId的flavor数量，用于判断是否全部删除
        // 需先进行统计，再删除，否则统计不到数据

        int sum = 0;
        for (String id : idsList) {
            if (StrUtil.isEmpty(id)) {
                continue;
            }
            int countFlavorsByDishId = dishFlavorDao.countFlavorsByDishId(id);
            sum += countFlavorsByDishId;
        }
        log.info("*********删除口味的总数为：" + Integer.toString(sum));

        log.info("*********删除菜品和口味,begin");
        int deleteById = dishDao.deleteById(idsList);
        int deleteByDishIds = dishFlavorDao.deleteByDishIds(idsList);

        log.info("*********删除菜品和口味,end");

        return deleteByDishIds == sum && deleteById == idsList.size();
    }

    @Override
    public boolean updateStatus(Integer status, List<String> idsList) {
        return dishDao.updateStatus(status, idsList) > 0;
    }

    @Override
    public List<DishVo> getByCategoryId(String categoryId) {
        if (StrUtil.isEmpty(categoryId)) {
            return null;
        }
        List<DishVo> dishVoList = dishDao.selectByCategoryId(categoryId);
        if (CollUtil.isEmpty(dishVoList)) {
            return null;
        }
        for (DishVo dishVo : dishVoList) {
            if (Objects.isNull(dishVo)) {
                continue;
            }

            //通过dishId获取口味集合
            String dishId = dishVo.getId();
            log.info("********通过菜品id查询口味，begin");
            List<DishFlavor> flavors = dishFlavorDao.selectByDishId(dishId);
            log.info("********通过菜品id查询口味，end");

            dishVo.setFlavors(flavors);
        }
        // for (DishVo dishVo : dishVoList) {
        //     if(Objects.isNull(dishVo)){
        //         continue;
        //     }
        //     String dishId = dishVo.getId();
        //     log.info("********通过菜品id查询口味，begin");
        //     List<DishFlavor> flavors = dishFlavorDao.selectByDishId(dishId);
        //     log.info("********通过菜品id查询口味，end");
        //
        //     dishVo.setFlavors(flavors);
        // }
        return dishVoList;
    }

    @Override
    public PageBean<DishVo> selectPage(Integer page, Integer pageSize, String name, String type) {
        //分页数据处理
        int begin = (page - 1) * pageSize;
        int size = pageSize;
        if (name != null && name.length() > 0) {
            name = "%" + name + "%";
        }

        log.info("********分页查询菜品表，begin");
        List<DishVo> dishVos = dishDao.selectPage(begin, size, name, type);
        int count = dishDao.pageCount();
        log.info("********分页查询菜品表，end");

        if (CollUtil.isEmpty(dishVos)) {
            return null;
        }

        for (DishVo dishVo : dishVos) {
            if (Objects.isNull(dishVo)) {
                continue;
            }

            //设置dishVo的id
            String dishId = dishVo.getId();
            log.info("********通过dishId查询口味表，begin");
            List<DishFlavor> flavors = dishFlavorDao.selectByDishId(dishId);
            log.info("********通过dishId查询口味表，end");
            if (CollUtil.isNotEmpty(flavors)) {
                dishVo.setFlavors(flavors);
            }

        }

        PageBean<DishVo> dishPageBean = new PageBean<>();
        dishPageBean.setRecords(dishVos);
        dishPageBean.setTotal(count);

        return dishPageBean;
    }

    @Override
    public DishVo selectByDishId(String id) {
        DishVo dishVo = dishDao.selectByDishId(id);
        if(Objects.isNull(dishVo)){
            return null;
        }

        List<DishFlavor> dishFlavors = dishFlavorDao.selectByDishId(dishVo.getId());
        if(CollUtil.isEmpty(dishFlavors)){
            dishVo.setFlavors(dishFlavors);
        }

        return dishVo;
    }


}
